#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <termios.h>

#include <error.h>
#include <pthread.h>

#include <sys/types.h>
#include <sys/stat.h>

#include "server.h"
#include "serial.h"

#define REQ_DATA_SIZE   32
#define HDR_DATA_SIZE   128

#include "serial.h"

#define ZGB_DATA_SIZE	36

int zigbee_get_dat(int fd)
{
	ssize_t ret;
	unsigned char buf[ZGB_DATA_SIZE];
	
	memset(buf, 0, sizeof(buf));
	ret = serial_recv(fd, buf, 36, sizeof(buf));
	if(ret == sizeof(buf)){
		/*int i;
		for (i = 0; i < 36; i++){
			printf("%.2x ", buf[i]);
		}
		printf("\n");*/
		
		if(buf[0] == 0xbb)
		{
			memset(&data, 0, sizeof(struct env));
			data.id = (int)buf[1];
			
			data.tem =  (int)buf[5] + buf[4] ;
			data.hum =  (int)buf[7] + buf[6] ;
			data.light =  (int)((buf[23] << 24) + (buf[22] << 16) + (buf[21] << 8) + buf[20]);
			if ( (data.x =  (int)buf[8]) > 127){
				data.x -= 256;
			}
			if ( (data.y =  (int)buf[9]) > 127){
				data.y -= 256;
			}
			if ( (data.z =  (int)buf[10]) > 127){
				data.z -= 256;
			}
		}
	}
	
	
	return ret;
}

int zigbee_exe_cmd(int fd, char *p)
{
	unsigned char buf[36] = {0xdd, 0x07, 0x24, 0x00, 0x04};
	//buf[1] = data.id;
	if (strstr(p, "Led_on") != NULL){
		buf[4] = 0x00;
	} else if (strstr(p, "Led_off") != NULL){
		buf[4] = 0x01;
	} else if (strstr(p, "Buzzer_on") != NULL){
		buf[4] = 0x02;
	} else if (strstr(p, "Buzzer_off") != NULL){
		buf[4] = 0x03;
	} else if (strstr(p, "Fan_on") != NULL){
		buf[4] = 0x04;
	} else if (strstr(p, "Fan_off") != NULL){
		buf[4] = 0x08;
	} else if (strstr(p, "SHU_ON") != NULL){
		buf[4] = 0x09;
	} else if (strstr(p, "SHU_OFF") != NULL){
		buf[4] = 0x0a;
	} 
	
	int ret = serial_send(fd, buf, sizeof(buf));
	
	return ret;
}

int zigbee_exit(int fd)
{
	return serial_exit(fd);
}
